import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertest/navigation_result.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import '../../utils/http_client.dart';
import 'package:device_info_plus/device_info_plus.dart';

class SkipStoreDialog extends StatefulWidget {
  final Function(String reason, List<String>) onConfirm;

  const SkipStoreDialog({super.key, required this.onConfirm});

  @override
  State<SkipStoreDialog> createState() => _SkipStoreDialogState();
}

class _SkipStoreDialogState extends State<SkipStoreDialog> {
  final _reasonController = TextEditingController();
  String? _imagePath;  // 改为单个图片路径
  List<String>? _uploadedImageUrl;  // 改为单个图片URL
  final _picker = ImagePicker();
  bool _isUploading = false;

  Future<void> _pickImage() async {
    try {
      // 检查是否在模拟器上运行
      if (Platform.isIOS) {
        bool isSimulator = false;
        final iosInfo = await DeviceInfoPlugin().iosInfo;
        isSimulator = !iosInfo.isPhysicalDevice;

        if (isSimulator) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('模拟器不支持相机功能，请使用真机测试')),
            );
          }
          return;
        }
      }

      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,  // 添加图片质量压缩
        maxWidth: 1024,    // 限制最大宽度
        maxHeight: 1024,   // 限制最大高度
      );

      if (image != null) {
        setState(() {
          _imagePath = image.path;
        });
        // 立即上传图片
        await _uploadImage(image.path);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('无法访问相机，请检查相机权限')),
        );
      }
    }
  }

  Future<void> _uploadImage(String imagePath) async {
    setState(() {
      _isUploading = true;
    });

    try {
      // 创建 FormData
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(
          imagePath,
          filename: 'skip_store_${DateTime.now().millisecondsSinceEpoch}.jpg',
        ),
      });
      // 上传图片
      var response = await HttpClient.externalDio.post(
        'https://jhshyy.jinhubianli.com/unite_platform/reservation/imagesOss2',
        data: formData,
      );
      response.data = json.decode(response.data);
      if (response.data['code'] == 0) {
        setState(() {
          _uploadedImageUrl = [response.data['data']];  // 保存返回的URL
        });
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '图片上传失败')),
          );
        }
      }
    } catch (e) {
      print(e);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('图片上传失败，请重试')),
        );
      }
    } finally {
      setState(() {
        _isUploading = false;
      });
    }
  }

  void _removeImage() {
    setState(() {
      _imagePath = null;
      _uploadedImageUrl = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('跳过原因'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _reasonController,
              decoration: const InputDecoration(
                labelText: '请输入跳过原因',
                hintText: '例如：店铺未营业',
              ),
              maxLines: 2,
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                const Text('现场照片'),
                const Spacer(),
                if (_isUploading)
                  const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                else
                  TextButton.icon(
                    onPressed: _imagePath == null ? _pickImage : null,  // 已有图片时禁用
                    icon: const Icon(Icons.camera_alt),
                    label: const Text('拍照'),
                  ),
              ],
            ),
            if (_imagePath != null)
              Stack(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(4),
                    child: Image.file(
                      File(_imagePath!),
                      height: 120,
                      width: double.infinity,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Positioned(
                    right: 0,
                    top: 0,
                    child: IconButton(
                      icon: const Icon(Icons.close, color: Colors.red),
                      onPressed: _removeImage,
                    ),
                  ),
                ],
              ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: _isUploading
              ? null
              : () {
            if (_reasonController.text.isEmpty) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('请输入跳过原因')),
              );
              return;
            }
            // if (_uploadedImageUrl == null) {
            //   ScaffoldMessenger.of(context).showSnackBar(
            //     const SnackBar(content: Text('请上传现场照片')),
            //   );
            //   return;
            // }
            widget.onConfirm(_reasonController.text, _uploadedImageUrl??[]);
            Navigator.pop<NavigationResult>(context,NavigationResult.refresh(
              message: "跳过"
            ));
          },
          child: _isUploading
              ? const SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2),
          )
              : const Text('确认'),
        ),
      ],
    );
  }
} 